package cn.fzkj.gulimall.product.service.impl;

import cn.fzkj.common.constant.ProductConstant;
import cn.fzkj.common.to.SkuReductionTo;
import cn.fzkj.common.to.SpuBoundsTo;
import cn.fzkj.common.to.es.SkuEsModel;
import cn.fzkj.common.utils.R;
import cn.fzkj.gulimall.product.entity.*;
import cn.fzkj.gulimall.product.feign.CouponFeignService;
import cn.fzkj.gulimall.product.feign.SearchFeignService;
import cn.fzkj.gulimall.product.feign.WareFeignService;
import cn.fzkj.gulimall.product.service.*;
import cn.fzkj.gulimall.product.vo.*;
import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.fzkj.common.utils.PageUtils;
import cn.fzkj.common.utils.Query;

import cn.fzkj.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService descService;
    @Autowired
    private SpuImagesService imagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService attrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public boolean saveSpuInfo(SpuVo spuVo) {
        // 1、保存商品基本信息 spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        // 2、保存商品描述信息【图片】 spu_info_descrip
        List<String> decript = spuVo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",", decript));
        descService.saveSpuInfoDesc(descEntity);

        // 3、保存spu图片集 spu_images
        List<String> images = spuVo.getImages();
        imagesService.saveImages(spuInfoEntity.getId(), images);

        // 4、保存spu规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity entity = new ProductAttrValueEntity();
            entity.setAttrId(attr.getAttrId());
            AttrEntity byId = attrService.getById(attr.getAttrId());
            entity.setAttrName(byId.getAttrName());
            entity.setAttrValue(attr.getAttrValues());
            entity.setAttrSort(attr.getShowDesc());
            entity.setSpuId(spuInfoEntity.getId());
            return entity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttrValue(collect);

        // 5、保存spu积分信息 sms_spu_bounds
        Bounds bounds = spuVo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if (!r.success()){
            log.warn("远程保存spu信息异常, 异常码 -> " + r.getCode() + ", 异常消息 -> " + r.getMsg());
        }

        // 5、保存spu的sku信息

        // 5.1、sku基本信息 sku_info
        List<Skus> skus = spuVo.getSkus();
        if (skus != null && skus.size() > 0){
            skus.forEach(sku -> {
                String defaultImg = "";
                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg() == 1){
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesEntity> skuImages = sku.getImages().stream().map(img -> {
                    SkuImagesEntity imagesEntity = new SkuImagesEntity();
                    imagesEntity.setSkuId(skuId);
                    imagesEntity.setImgUrl(img.getImgUrl());
                    imagesEntity.setDefaultImg(img.getDefaultImg());
                    return imagesEntity;
                }).filter(item -> {
                    // 过滤掉没有图片路径的数据
                    return StringUtils.isNotEmpty(item.getImgUrl());
                }).collect(Collectors.toList());

                // 5.2、sku图片信息 sku_images
                skuImagesService.saveBatch(skuImages);

                // 5.3、sku销售属性信息 sku_sale_attr_value
                List<Attr> attrs = sku.getAttr();
                List<SkuSaleAttrValueEntity> valueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(valueEntities);


                // 5.4、sku的优惠信息【远程调用】 sku
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                    R res = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (!res.success()){
                        log.warn("远程保存sku信息异常, 异常码 -> " + res.getCode() + ", 异常消息 -> " + res.getMsg());
                    }
                }
            });
        }
        return false;
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        /**
         * status: 0
         * key:
         * brandId: 12
         * catelogId: 225
         */

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)){
            wrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && Integer.parseInt(brandId) != 0){
            wrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && Integer.parseInt(catelogId) != 0){
            wrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架
     * @param spuId
     * @return
     */
    @Override
    public boolean up(Long spuId) {

        // 1、查处当前spuId对应的所有sku信息，品牌的名字
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);

        // 查询当前 sku的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = attrValueService.getAttrListForSpu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(attr -> attr.getAttrId()).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);

        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(baseAttr -> {
            return searchAttrIds.contains(baseAttr.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());

        // 远程调用查看sku库存信息

        Map<Long, Boolean> skuStockTemp = null;
        try {
            List<Long> skuAttrIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
            R r = wareFeignService.hasStock(skuAttrIds);

            List<SkuStockVo> data = (List<SkuStockVo>)r.get("data");
            if (!CollectionUtils.isEmpty(data)){
                skuStockTemp = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
            }

        }catch (Exception e){
            log.warn("查询库存系统异常 -> {}", e);
        }

        // 2、封装sku信息
        Map<Long, Boolean> finalSkuStockTemp = skuStockTemp;
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());

            // 先给0
            skuEsModel.setHotScore(0L);
            if (finalSkuStockTemp == null){
                skuEsModel.setHasStock(false);
            }else {
                skuEsModel.setHasStock(finalSkuStockTemp.get(sku.getSkuId()));
            }

            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());

            // 设置检索属性
            skuEsModel.setAttrs(attrsList);

            return skuEsModel;
        }).collect(Collectors.toList());

        // 调用es完成保存
        R r = searchFeignService.productsUp(upProducts);
        if(r.getCode() == 0){
            // 修改spu的状态为已上架
            SpuInfoEntity entity = new SpuInfoEntity();
            entity.setId(spuId);
            entity.setUpdateTime(new Date());
            entity.setPublishStatus(ProductConstant.StatusEnum.SPU_UP.getCode());
            this.baseMapper.updateById(entity);
        }else {
            // TODO 异常重试？？【接口幂等性】
        }

        return false;
    }

    @Override
    public boolean saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {

        this.baseMapper.insert(spuInfoEntity);
        return true;
    }

}